import {Message} from "element-ui";
/**
 * 结果映射
 */
const resultMap = {
    data: "data",
    message: 'msg',
    code: "code"
} , status = {
    ok: [200],
    error:[500,404],
    noAuth: [401]
}

function isSuccess(res){
    return res.status
}
function getMsg(res){
    return res.msg || (isSuccess(res) ? "操作成功": '操作失败')
}
function getMsgType(res){
    return isSuccess(res)?'success': 'error'
}

function normalization(res){
    return {
        msg: res[resultMap.message] ,
        data: res[resultMap.data],
        status: isSuccess(res),
        code: res[resultMap.code]
    }
}

class ApiResponse {
    constructor(res){
        this.result = normalization(res) ;
    }
    ok(fn){
        if(isSuccess(this.result)){
            fn && fn(this.result.data) ;
        }
        return this ;
    }
    error(fn){
        if(!isSuccess(this.result)){
            fn && fn(this.result.msg) ;
        }
        return this ;
    }
    execute(ok,error){
        if(isSuccess(this.result)){
            ok && ok(this.result.data) ;
        }else {
            error && error(this.result.msg) ;
        }
        return this ;
    }
    print(msg){
        Message({
            message: msg || getMsg(this.result) ,
            type: getMsgType(this.result),
            duration: 5 * 1000
        })
        return this ;
    }
}
ApiResponse.init = function (res){
    return new ApiResponse(res)
}
export default ApiResponse
